import React, { useEffect, useState, useRef } from 'react';
import { useDashboardStore, initializeUrlSync } from '../store/dashboardStore';
import { FilterPanel } from './FilterPanel';
import styles from './Dashboard.module.css';
import type { CircleIndicator } from '../types';

const Filtera: React.FC = () => {
  const {
    filters,
    isLoading,
    circleIndicators,
    centralDashboard,
    tableData,
    leftPanelData,
    rightPanelData,
    isFilterVisible,
    isAnimating,
    availableRegions,
    availableStores,
    availableTimeRanges,
    userPermission,
    setFilterVisible,
    updateCentralRotation,
    setAnimating,
    loadData,
    setFilters
  } = useDashboardStore();

  const [rotation, setRotation] = useState<number>(0);
  const [isAutoRotating, setIsAutoRotating] = useState<boolean>(true);
  const [hoveredIndicator, setHoveredIndicator] = useState<string | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState<{x: number, y: number}>({x: 0, y: 0});
  const [currentTime, setCurrentTime] = useState<string>('');
  const [isInitialized, setIsInitialized] = useState<boolean>(false);
  const [showScrollIndicator, setShowScrollIndicator] = useState<boolean>(true);
  // 添加滚动方向状态
  const [scrollDirectionDown, setScrollDirectionDown] = useState<boolean>(true);
  const rotationRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const centralRef = useRef<HTMLDivElement>(null);
  const dataUpdateRef = useRef<ReturnType<typeof setInterval> | null>(null);

  // 初始化
  useEffect(() => {
    // 初始化URL同步
    initializeUrlSync();
    
    // 立即加载数据
    if (!isInitialized) {
      loadData();
      setIsInitialized(true);
    }
    
    // 设置当前时间
    setCurrentTime(new Date().toLocaleTimeString());
    
    // 定时更新时间
    const timeInterval = setInterval(() => {
      setCurrentTime(new Date().toLocaleTimeString());
    }, 1000);

    // 定时更新数据
    dataUpdateRef.current = setInterval(() => {
      if (!isAnimating) {
        loadData();
      }
    }, 10000); // 每10秒更新一次数据

    // 滚动监听器
    const handleScroll = () => {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;
      
      // 当滚动到页面80%时隐藏指示器
      if (scrollTop + windowHeight >= documentHeight * 0.8) {
        setShowScrollIndicator(false);
      } else {
        setShowScrollIndicator(true);
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      clearInterval(timeInterval);
      if (dataUpdateRef.current) {
        clearInterval(dataUpdateRef.current);
      }
      window.removeEventListener('scroll', handleScroll);
    };
  }, [isAnimating, loadData, isInitialized]);

  // 自动旋转逻辑
  useEffect(() => {
    if (isAutoRotating && !isAnimating) {
      rotationRef.current = setInterval(() => {
        setRotation(prev => {
          const newRotation = (prev + 0.5) % 360;
          updateCentralRotation(newRotation);
          return newRotation;
        });
      }, 50);
    } else {
      if (rotationRef.current) {
        clearInterval(rotationRef.current);
      }
    }

    return () => {
      if (rotationRef.current) {
        clearInterval(rotationRef.current);
      }
    };
  }, [isAutoRotating, isAnimating, updateCentralRotation]);

  // 处理中央圆盘点击
  const handleCentralClick = () => {
    setIsAutoRotating(false);
    setAnimating(true);
    
    // 模拟数据刷新
    setTimeout(() => {
      loadData();
      setAnimating(false);
      setIsAutoRotating(true);
    }, 12000);
  };

  // 处理圆形指标点击
  const handleCircleClick = (indicator: CircleIndicator) => {
    setAnimating(true);
    // 模拟数据变化
    setTimeout(() => {
      loadData();
      setAnimating(false);
    }, 1000);
  };

  // 处理鼠标悬停
  const handleCircleHover = (indicator: CircleIndicator | null, event?: React.MouseEvent) => {
    setHoveredIndicator(indicator?.id || null);
    if (event && indicator) {
      setTooltipPosition({
        x: event.clientX,
        y: event.clientY
      });
    }
  };

  // 处理鼠标滑动
  const handleMouseMove = (e: React.MouseEvent) => {
    if (!centralRef.current) return;
    
    const rect = centralRef.current.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    const deltaX = e.clientX - centerX;
    const deltaY = e.clientY - centerY;
    
    const angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI);
    const normalizedAngle = (angle + 360) % 360;
    
    setIsAutoRotating(false);
    setRotation(normalizedAngle);
    updateCentralRotation(normalizedAngle);
  };

  // 鼠标离开中央区域时恢复自动旋转
  const handleMouseLeave = () => {
    setTimeout(() => {
      setIsAutoRotating(true);
    }, 2000);
  };

  // 平滑滚动到表格区域
  const scrollToTable = () => {
    const tableElement = document.querySelector(`.${styles.bottomArea}`);
    if (tableElement) {
      tableElement.scrollIntoView({ 
        behavior: 'smooth',
        block: 'start'
      });
    }
  };

  // 新增滚动控制函数
  const handleScrollButtonClick = () => {
    if (scrollDirectionDown) {
      scrollToTable();
    } else {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    setScrollDirectionDown(!scrollDirectionDown);
  };

  // 渲染状态标签
  const renderStatusBadge = (status: string) => {
    const statusClass = {
      '正常': styles.statusNormal,
      '警告': styles.statusWarning,
      '异常': styles.statusError
    }[status] || styles.statusNormal;

    return <span className={statusClass}>{status}</span>;
  };

  // 渲染进度条
  const renderProgressBar = (percentage: number, color: string) => (
    <div className={styles.progressBar}>
      <div 
        className={styles.progressFill} 
        style={{ 
          width: `${percentage}%`, 
          backgroundColor: color,
          boxShadow: `0 0 10px ${color}` 
        }}
      />
    </div>
  );

  // 渲染tooltip
  const renderTooltip = () => {
    const indicator = circleIndicators.find(ind => ind.id === hoveredIndicator);
    if (!indicator) return null;

    return (
      <div 
        className={styles.tooltip}
        style={{
          left: tooltipPosition.x + 10,
          top: tooltipPosition.y - 10
        }}
      >
        <div className={styles.tooltipTitle}>{indicator.title}</div>
        <div className={styles.tooltipContent}>
          <div>当前值: {indicator.value} {indicator.unit}</div>
          <div>最大值: {indicator.maxValue} {indicator.unit}</div>
          <div>完成度: {indicator.percentage}%</div>
        </div>
      </div>
    );
  };

  // 如果数据未加载完成，显示加载界面
  if (!isInitialized || (isLoading && tableData.length === 0)) {
    return (
      <div className={styles.dashboard}>
        <div className={styles.loading}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>正在加载数据...</div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.dashboard}>
      {/* 背景装饰 */}
      <div className={styles.techBorder}></div>

      {/* 标题和时间 */}
      <div className={styles.header}>
        {/* <h1 className={styles.title}>智能超市数据分析系统</h1> */}
        {/* <div className={styles.timeDisplay}>{currentTime}</div> */}
        {/* 筛选器按钮 */}
        <button
          className={styles.filterButton}
          onClick={() => setFilterVisible(true)}
        >
          <span className={styles.filterIcon}>⚙</span>
          筛选器
        </button>
        <div className={styles.filterInfo}>
          筛选条件: {filters.region} | {filters.store} | {filters.timeRange}
        </div>
      </div>

      {/* 全局筛选栏 */}
      <div className={styles.globalFilterBar}>
        <div className={styles.quickFilters}>
          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>区域</label>
            <select
              className={styles.quickSelect}
              value={filters.region}
              onChange={(e) =>
                setFilters({ ...filters, region: e.target.value })
              }
            >
              {availableRegions
                .filter(
                  (region) =>
                    region === "全部" ||
                    userPermission.canViewAll ||
                    userPermission.region.includes(region)
                )
                .map((region) => (
                  <option key={region} value={region}>
                    {region}
                  </option>
                ))}
            </select>
          </div>

          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>门店</label>
            <select
              className={styles.quickSelect}
              value={filters.store}
              onChange={(e) =>
                setFilters({ ...filters, store: e.target.value })
              }
            >
              {availableStores
                .filter(
                  (store) =>
                    store === "全部" ||
                    userPermission.canViewAll ||
                    userPermission.store.includes(store)
                )
                .map((store) => (
                  <option key={store} value={store}>
                    {store}
                  </option>
                ))}
            </select>
          </div>

          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>时间</label>
            <select
              className={styles.quickSelect}
              value={filters.timeRange}
              onChange={(e) =>
                setFilters({ ...filters, timeRange: e.target.value })
              }
            >
              {availableTimeRanges.map((range) => (
                <option key={range} value={range}>
                  {range}
                </option>
              ))}
            </select>
          </div>

          <button
            className={styles.refreshButton}
            onClick={() => loadData()}
            disabled={isLoading}
          >
            <span className={styles.refreshIcon}>🔄</span>
            刷新数据
          </button>

          <button
            className={styles.advancedFilterButton}
            onClick={() => setFilterVisible(true)}
          >
            <span className={styles.filterIcon}>⚙</span>
            高级筛选
          </button>

          <button
            className={styles.exportButton}
            onClick={() => useDashboardStore.getState().exportData()}
            disabled={!userPermission.canExport}
          >
            <span className={styles.exportIcon}>📊</span>
            导出数据
          </button>
        </div>
      </div>

      {/* 主要布局 */}
      <div className={styles.grid}>
        {/* 左侧面板 */}
        <div className={styles.leftPanel}>
          <div className={styles.panelTitle}>
            <span className={styles.titleIcon}>📊</span>
            {leftPanelData.title}
          </div>
          <div className={styles.panelContent}>
            {leftPanelData.items.map((item, index) => (
              <div
                key={index}
                className={styles.panelItem}
                style={{ animationDelay: `${index * 0.1}s` }}
              >
                <div className={styles.itemHeader}>
                  <span className={styles.panelLabel}>{item.label}</span>
                  <span
                    className={styles.panelValue}
                    style={{ color: item.color }}
                  >
                    {item.value}
                  </span>
                </div>
                {item.label.includes("率") || item.label.includes("负载")
                  ? renderProgressBar(
                      parseFloat(item.value.toString().replace(/[^\d.]/g, "")),
                      item.color || "#00ffff"
                    )
                  : null}
              </div>
            ))}
          </div>
        </div>

        {/* 中央区域 */}
        <div className={styles.centralArea}>
          {/* 圆形指标 */}
          <div className={styles.circleIndicators}>
            {circleIndicators.map((indicator, index) => {
              const positions = [
                "topLeft",
                "topRight",
                "bottomLeft",
                "bottomRight",
              ];
              return (
                <div
                  key={indicator.id}
                  className={`${styles.circleIndicator} ${
                    styles[positions[index]]
                  } ${hoveredIndicator === indicator.id ? styles.hovered : ""}`}
                  onClick={() => handleCircleClick(indicator)}
                  onMouseEnter={(e) => handleCircleHover(indicator, e)}
                  onMouseLeave={() => handleCircleHover(null)}
                  onMouseMove={(e) => handleCircleHover(indicator, e)}
                >
                  <div className={styles.circleTitle}>{indicator.title}</div>
                  <div className={styles.circleValue}>{indicator.value}</div>
                  <div className={styles.circleUnit}>{indicator.unit}</div>
                  {renderProgressBar(indicator.percentage, indicator.color)}
                  <div className={styles.circlePercentage}>
                    {indicator.percentage}%
                  </div>
                </div>
              );
            })}
          </div>

          {/* 中央仪表盘 */}
          <div
            className={styles.centralDashboard}
            ref={centralRef}
            onClick={handleCentralClick}
            onMouseMove={handleMouseMove}
            onMouseLeave={handleMouseLeave}
          >
            <div className={styles.decorativeRings}></div>
            <div
              className={styles.mainCircle}
              style={{
                transform: `rotate(${rotation}deg)`,
                transition: isAnimating
                  ? "transform 0.5s ease"
                  : isAutoRotating
                  ? "none"
                  : "transform 0.3s ease",
              }}
            ></div>
            <div className={styles.centralContent}>
              <div className={styles.centralValue}>
                {centralDashboard.mainValue.toLocaleString()}
              </div>
              <div className={styles.centralUnit}>
                {centralDashboard.mainUnit}
              </div>
              <div className={styles.subValues}>
                {centralDashboard.subItems.slice(0, 3).map((item, index) => (
                  <div
                    key={index}
                    className={styles.subValue}
                    style={{ color: item.color }}
                  >
                    {item.label}: {item.value}%
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 右侧面板 */}
        <div className={styles.rightPanel}>
          <div className={styles.panelTitle}>
            <span className={styles.titleIcon}>📈</span>
            {rightPanelData.title}
          </div>
          <div className={styles.panelContent}>
            {rightPanelData.items.map((item, index) => (
              <div
                key={index}
                className={styles.panelItem}
                style={{ animationDelay: `${index * 0.1}s` }}
              >
                <div className={styles.itemHeader}>
                  <span className={styles.panelLabel}>{item.label}</span>
                  <span
                    className={styles.panelValue}
                    style={{ color: item.color }}
                  >
                    {item.value}
                  </span>
                </div>
                {item.label.includes("率") || item.label.includes("增长")
                  ? renderProgressBar(
                      Math.abs(
                        parseFloat(item.value.toString().replace(/[^\d.]/g, ""))
                      ),
                      item.color || "#00ffff"
                    )
                  : null}
              </div>
            ))}
          </div>
        </div>

        {/* 底部数据表格 */}
        <div className={styles.bottomArea}>
          <div className={styles.tableHeader}>
            <span className={styles.titleIcon}>📋</span>
            实时数据监控表
            <span className={styles.tableCount}>
              ({tableData.length}条记录)
            </span>
          </div>
          <div className={styles.tableContainer}>
            <table className={styles.dataTable}>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>门店名称</th>
                  <th>数据日期</th>
                  <th>运营状态</th>
                  <th>业务类别</th>
                  <th>销售额(万)</th>
                </tr>
              </thead>
              <tbody>
                {tableData.map((row, index) => (
                  <tr
                    key={row.id}
                    style={{ animationDelay: `${index * 0.1}s` }}
                  >
                    <td>{row.serialNumber}</td>
                    <td className={styles.storeName}>{row.name}</td>
                    <td>{row.date}</td>
                    <td>{renderStatusBadge(row.status)}</td>
                    <td className={styles.category}>{row.category}</td>
                    <td className={styles.amount}>
                      {(row.amount / 10000).toFixed(2)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* 筛选器面板 */}
      <FilterPanel
        visible={isFilterVisible}
        onClose={() => setFilterVisible(false)}
      />

      {/* 加载动画 */}
      {isLoading && (
        <div className={styles.loading}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>数据加载中...</div>
        </div>
      )}

      {/* Tooltip */}
      {hoveredIndicator && renderTooltip()}

      {/* 滚动提示指示器 */}
      {showScrollIndicator && (
        <div className={styles.scrollIndicator} onClick={handleScrollButtonClick}>
          <div className={styles.scrollArrow}>{scrollDirectionDown ? '⬇' : '⬆'}</div>
          <div className={styles.scrollText}>{scrollDirectionDown ? '向下滚动查看表格' : '向上滚动回到顶部'}</div>
        </div>
      )}

      {/* 数值显示 */}
      {/* <div className={`${styles.cornerNumber} ${styles.topLeft}`}>
        {Math.floor(Math.random() * 100) + 100}
      </div>
      <div className={`${styles.cornerNumber} ${styles.bottomLeft}`}>
        {Math.floor(Math.random() * 100) + 100}
      </div>
      <div className={`${styles.cornerNumber} ${styles.rightCenter}`}>
        {Math.floor(Math.random() * 1000) + 1000}
      </div> */}
    </div>
  );
};

export default Filtera;